import { useState, useEffect } from 'react'
import { Input, Button, Space, Tooltip, message } from 'antd'
import s from "./index.module.less";
import { bianliangEnum } from "@/utils/enum";
import { versionPathOperation } from "@/utils/index";
import { useParams } from 'react-router-dom';

function App(): JSX.Element {
  const params: any = useParams();
  const [loading, setLoading] = useState(false)
  const [addButtonList, setAddButtonList] = useState<any[]>([])
  const [config, setConfig] = useState<any>({
    versionPath: versionPathOperation.get('versionPath'),
    path: versionPathOperation.get('config'),
    bianliangEnum: bianliangEnum
  })

  const saveS = (config) => {
    versionPathOperation.save('N17', config.bianliangEnum?.N17?.val)
    versionPathOperation.save('zhucheng_code', config.bianliangEnum?.$$主城地图代码?.val)
  }

  useEffect(() => {
    if (params.type !== 'old') {
      const newBianliangEnum = window.api.getBianLiangVal(config)
      
      const c = {
        ...config,
        bianliangEnum: newBianliangEnum
      }
      saveS(c)
      setConfig(c)
    }
  }, [config.versionPath])

  return (
    <div className={s.box} style={{ minWidth: 400 }}>
      <h1>变量替换</h1>
      <Space>
        <div>
          <p>版本服务器所在路径:</p>
          <div className='flex'>
            <Input size='small' spellCheck="false" value={config.versionPath} />

            <div className='file-box'>
              <Button size='small' type='primary' onClick={() => {
                const c = {
                  ...config
                }
                c.versionPath = window.api.syncOperationWindow('selectDirectory')
                versionPathOperation.save('versionPath', c.versionPath)
                setConfig(c)
              }}>浏览</Button>
            </div>
          </div>
        </div>
        <div>
          <p>默认替换的是软件内置的配置文件(也可自己上传):</p>
          <div className='flex'>
            <Input
              spellCheck="false"
              size='small'
              value={config.path}
            />

            <div className='file-box'>
              <Button size='small' type='primary' onClick={() => {
                const c = {
                  ...config
                }
                c.path = window.api.syncOperationWindow('selectDirectory')
                versionPathOperation.save('config', c.path)
                setConfig(c)
              }}>浏览</Button>
            </div>
          </div>
        </div>
      </Space>

      <div>
        {
          Object.keys(config?.bianliangEnum).map((key) => {
            const item = config.bianliangEnum[key]
            return (
              <div key={key} className={`flex ${s.bl}`} style={{ marginBottom: 10 }}>
                <p style={{ flex: 'none' }}>
                  {key}
                  换成
                  →
                </p>
                <Input
                  spellCheck="false"
                  size='small'
                  value={item.val}
                  placeholder={item.p || item.tip || ''}
                  onChange={(e) => {
                    const bianliangEnum = {
                      ...config.bianliangEnum
                    }
                    bianliangEnum[key].val = e.target.value
                    setConfig({
                      ...config,
                      bianliangEnum
                    })
                  }}
                />

                {item.tip && <span className={s.tip}>
                  {item.tip}
                </span>}
              </div>
            )
          })
        }
      </div>

      <Space>
        <Tooltip title='注意，点击替换后，输入的变量会缓存在本地，下次打开选择版本路径会直接回填你之前输入的变量'>
          <Button type='primary' size='small' loading={loading} onClick={() => {
            setLoading(true)
            setTimeout(() => {
              window.api.saveBianliang(config)
            }, 100)
            setTimeout(async () => {
              await window.api.tihuanBianliang(config, (is) => {
                if (is) {
                  saveS(config)
                } else {
                  message.error('请输入路径')
                  setLoading(false)
                  return
                }
                setTimeout(() => {
                  message.success('修改成功')
                  setLoading(false)
                }, 500)
              })
            }, 2100)
          }}>替换模板中的所有变量</Button>
        </Tooltip>

        {params.type !== 'old' ? <Button size='small' onClick={async () => {
          await window.api.delCacheBianliang(config, (is) => {
            if (is) {
              message.success('删除成功')
              location.reload()
            } else {
              message.error('请输入路径')
            }
          })
        }}>删除缓存</Button> : ''}
      </Space>

      <div className={s.viewButtom}>
        {params.type !== 'old' ? <Button size='small' loading={loading} onClick={() => {
          setLoading(true)
          setTimeout(() => {
            window.api.saveBianliang(config)
          }, 100)
          setTimeout(async () => {
            const data = await window.api.lookup(config)
            setLoading(false)
            console.log(data, 'datadatadata');
            setAddButtonList(data)
          }, 600)
        }}>
          获取使用过的按钮编号
        </Button> : ''}

        {addButtonList.length ? 
          <>
            <div className={s.tongji}>
              按钮使用统计:（{addButtonList?.[0]?.tongji?.join('    ')}）
            </div>
            <div className={s.main}>
              <h3>使用的按钮所在文件：</h3>
              {
                addButtonList?.map((item, i) => {
                  return (
                    <div style={{ marginBottom: 20 }} key={`${item.file}${i}`}>
                      <h2>文件: {item.file}</h2>
                      {
                        item.buttonList.map((item2, i2) => {
                          return (<Space key={`${item2.context}${i2}`}>
                            <span>代码: {item2.context}</span>
                            <span style={{ color: "red" }}>按钮编号: {item2.val}</span>
                          </Space>)
                        })
                      }
                    </div>
                  )
                })
              }
            </div>
          
          </>
        : ''}
      </div>
    </div>
  )
}

export default App
